<?php

namespace App\Console\Commands\Tools\Camera;

use App\Kuafu\Shop\Service\CameraLibrary\YlCamera;
use Illuminate\Console\Command;

class RefreshYlCameraChannel extends Command
{
    protected $signature   = 'tools:refresh-yl-camera-channel';
    protected $description = '刷新影流摄像头通道信息';

    protected static string $queueName = '{RMS-UPDATE-YL-CAMERA-QUEUE}';

    private array $resetShopList = [];

    public function handle()
    {

        if (!isProd()) {
            $this->info('非生产环境不执行');
            return;
        }

        // 拉取影流所有的门店列表
        $camera = new YlCamera(null);

        $deviceListResult = $camera->getDeviceList();

        $deviceList = $deviceListResult['list'];

        foreach ($deviceList as $item) {
            if (!$this->checkNeedCheck($item)) {
                continue;
            }

            if ($item['channelCount'] != 1) {
                continue;
            }
//
//            if (
//                $item['deviceId'] != '31022910241110000003'
//            ) {
//                continue;
//            }

//            dump($item['deviceId']);

            // 触发更新任务
            $syncResult = $camera->postDeviceChannelsListSync($item['deviceId']);

            // 触发更新渠道
            dispatch(function () use ($item) {
                $camera = new YlCamera(null);

                // 默认更新成功了
                $deviceChannel = $camera->getDeviceChannelsList($item['deviceId'])['list'];
                foreach ($deviceChannel as $channelInfo) {
                    //
                    if (strlen($channelInfo['channelId']) < 10) {
                        continue;
                    }

                    if (strpos($channelInfo['name'], 'Channel') !== false) {
                        continue;
                    }

                    if (strpos($channelInfo['name'], '前端报警输入') !== false) {
                        continue;
                    }

                    $camera->postUpdateDeviceChannel($item['deviceId'], [
                        'channelId' => $channelInfo['channelId'],
                        'hasAudio'  => true,
                        'status'    => true
                    ]);

                }
            })->onQueue(self::$queueName)->delay(120);
        }
    }

    private function checkNeedCheck(array $item): bool
    {
        if (empty($item) || empty($item['name'])) {
            return false;
        }

        $explodeName = explode('-', $item['name']);
        $shopCode    = $explodeName[0] ?? '';
        if (!is_numeric($shopCode) || empty($shopCode)) {
            return false;
        }

        if (empty($item['name'])) {
            return false;
        }

        // 离线设备不校验


        return true;
    }
}
